import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import Vant from 'vant'
import 'vant/lib/index.css'
import '@vant/touch-emulator'

import App from './App.vue'
import router from './router'
import { initDatabase } from './utils/database'
import { autoCheckUpdate } from './utils/appUpdate'

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(Vant)

// 先立即挂载应用，显示UI
app.mount('#app')
console.log('🚀 应用UI已挂载')

// 后台初始化数据库
const initApp = async () => {
  try {
    // 等待Cordova准备就绪
    const isCordova = !!(window as any).cordova
    console.log('🔍 检测环境:', isCordova ? 'Cordova' : '浏览器')

    if (isCordova) {
      console.log('⏳ 等待deviceready事件...')
      await new Promise((resolve) => {
        if ((document as any).deviceready) {
          // 已经ready
          resolve(true)
        } else {
          document.addEventListener('deviceready', () => {
            console.log('✅ deviceready事件触发')
            resolve(true)
          }, false)
        }

        // 10秒超时
        setTimeout(() => {
          console.warn('⚠️ deviceready超时')
          resolve(false)
        }, 10000)
      })

      console.log('📱 Cordova已就绪')
      console.log('🔍 检查SQLite插件:', !!(window as any).sqlitePlugin ? '存在' : '不存在')
    }

    // 初始化数据库
    console.log('🗄️ 开始初始化数据库...')
    await initDatabase()
    console.log('✅ 数据库初始化成功')
    console.log('✅ 应用初始化完成')
    
    // 设置全局标志
    ;(window as any).databaseReady = true
    
    // 发送数据库准备完成事件
    window.dispatchEvent(new Event('database-ready'))
    console.log('📢 已发送database-ready事件')
    
    // 延迟3秒后自动检查更新（避免影响启动速度）
    setTimeout(() => {
      autoCheckUpdate().catch(err => console.log('自动检查更新失败:', err))
    }, 3000)
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error)
    alert(`数据库初始化失败: ${error}`)
  }
}

// 后台初始化
initApp()
